﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using FisheryPlatform.Bussiness.Account;
using FisheryPlatform.Entity;
using System.Web;
using FisheryPlatform.Common;
using FisheryPlatform.SiteConfig;

namespace FisheryPlatform.Bussiness.LoginCookie
{
    public class LoginCookieManager
    {
        public static string CookieDomain
        {
            #region
            get
            {
                if (!string.IsNullOrEmpty(SiteConfigManager.AppSettings["CookieDomain"].Value))
                {
                    return SiteConfigManager.AppSettings["CookieDomain"].Value;
                }
                return "";
            }
            #endregion
        }

        public static string CookieName
        {
            #region
            get
            {
                if (!string.IsNullOrEmpty(SiteConfigManager.AppSettings["CookieName"].Value))
                {
                    return SiteConfigManager.AppSettings["CookieName"].Value;
                }
                return "";
            }
            #endregion
        }

        /// <summary>
        /// Cookie DES 8位密钥
        /// </summary>
        public static string SecretKey
        {
            #region
            get
            {
                var defaultKey = SiteConfigManager.AppSettings["CookieSecretKey"].Value ?? "kanyecun";
                return defaultKey;
            }
            #endregion
        }

        /// <summary>
        /// 0:失败 1成功
        /// </summary>
        public static LoginResultEnum SignIn(string loginName, string password)
        {
            #region
            if (string.IsNullOrEmpty(loginName))
            {
                return LoginResultEnum.LoginNameIsEmpty;
            }

            if (string.IsNullOrEmpty(password))
            {
                return LoginResultEnum.PasspordIsEmpty;
            }

            UsersEntity user = UserManager.GetUserInfo(loginName, password);
            if (user == null || user.UserId <= 0)
            {
                return LoginResultEnum.Failure;
            }
            HttpContext.Current.Items.Add("_UserId_", user.UserId);

            string ipString = IPAddressUtility.GetClientIpFrom(HttpContext.Current.Request);
            long ip = IPAddressUtility.ConvertToLong(ipString);
            Guid smartID = new Guid(); //TradingPassport.Create(user.UserID, ip);

            if (!AddLoginUserInfoToCookie(smartID, user))
            {
                return LoginResultEnum.WriteDataToCookieFailure;
            }

            return LoginResultEnum.Success;
            #endregion
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void SignOut()
        {
            #region

            var request = HttpContext.Current.Request;
            var response = HttpContext.Current.Response;

            HttpCookie cookie = request.Cookies[CookieName];
            if (cookie != null)
            {
                cookie.Domain = CookieDomain;
                cookie.Values.Clear();
                cookie.Expires = DateTime.Now.AddYears(-10);
                response.Cookies.Add(cookie);
            }

            System.Web.Security.FormsAuthentication.SignOut();

            #endregion
        }

        private static bool AddLoginUserInfoToCookie(Guid smartID, UsersEntity user)
        {
            #region
            try
            {
                var request = HttpContext.Current.Request;
                var response = HttpContext.Current.Response;

                HttpCookie cookie = request.Cookies[CookieName];
                if (cookie != null)
                {
                    cookie.Values.Clear();
                    response.Cookies.Remove(CookieName);
                }
                else
                {
                    cookie = new HttpCookie(CookieName);
                }
                cookie.Domain = CookieDomain;
                
                cookie.Values.Add(CookieKeyConstants.SmartIDConstant, smartID.ToString());
                cookie.Values.Add(CookieKeyConstants.UserIDConstant, user.UserId.ToString());
                cookie.Values.Add(CookieKeyConstants.UserNameConstant, HttpUtility.UrlEncode(user.LoginName));
                cookie.Values.Add(CookieKeyConstants.RealNameConstant, HttpUtility.UrlEncode(user.RealName));
                response.Cookies.Add(cookie);

                //角色
                //var roleString = "";
                //System.Web.Security.FormsAuthenticationTicket rolesTicket = new System.Web.Security.FormsAuthenticationTicket(
                //    1,
                //    user.UserId.ToString(),
                //    DateTime.Now,
                //    DateTime.Now.AddMinutes(30),
                //    false,
                //    roleString
                //    );

                //HttpCookie roleCookie = request.Cookies[RoleCookieName];
                //if (roleCookie != null)
                //{
                //    roleCookie.Values.Clear();
                //    response.Cookies.Remove(RoleCookieName);
                //}
                //else
                //{
                //    roleCookie = new HttpCookie(RoleCookieName);
                //}
                //roleCookie.Domain = CookieDomain;
                //roleCookie.Value = System.Web.Security.FormsAuthentication.Encrypt(rolesTicket);
                //response.Cookies.Add(roleCookie);
                System.Web.Security.FormsAuthentication.SetAuthCookie(user.UserId.ToString(), false, "/");

                //System.Web.Security.FormsAuthentication.RedirectFromLoginPage(user.UserID.ToString(), false, "/");
                //System.Web.Security.FormsAuthentication.EnableCrossAppRedirects
                return true;
            }
            catch (Exception e)
            {
                ExceptionMessage.Record(e);
            }

            return false;

            #endregion
        }

        public static string GetValueFromCookie(string key)
        {
            #region

            var request = HttpContext.Current.Request;
            var response = HttpContext.Current.Response;

            HttpCookie cookie = request.Cookies[CookieName];
            if (cookie != null && cookie.Values[key] != null)
            {
                return HttpUtility.UrlDecode(cookie.Values[key].Trim());//alter by lizunjing
            }

            return "";

            #endregion
        }

    }
}
